//导入路由函数
import { createRouter, createWebHistory, useRouter, type RouteRecordRaw } from "vue-router"
import { useToken } from '@/stores/token' //导入token状态文件


//定义路由规则
const routes:Array<RouteRecordRaw> = [
    {
        path:"/",
        component:()=>import("@/views/Layout/index.vue"),
        children:[
            {
                path:"",
                component:()=>import("@/views/Index/index.vue")
            },
            {
                path:"/category/:id",
                component:()=>import("@/views/Category/index.vue")
            },
            {
                path:"/cart",
                component:()=>import("@/views/Cart/index.vue"),
                //路由独享守卫
                beforeEnter:()=>{
                    //执行方法获得tokenStore对象
                    const tokenStore = useToken()
                    //判断用户登录状态
                    if(tokenStore.token){
                        //已登录，正常放行
                        return true
                    }
                    else{
                        //未登录，跳转到登录页面
                        const router = useRouter();
                        router.push("/login")
                    }
                }
            }
        ]
    },
    {
        path:"/login",
        component:()=>import("@/views/Login/index.vue")
    }
];


//创建路由
const router = createRouter({
    history:createWebHistory(),
    routes
});

//导出路由
export default router
